﻿
using System.Collections.Generic;
namespace ImageConverter.Pooling
{
    public static class DimensionsPool
    {
        public static Dimensions Create(int width, int height)
        {
            return pool.Create(width, height);
        }

        private static DimensionsPoolInternal pool = new DimensionsPoolInternal();
    }

    internal class DimensionsPoolInternal
    {
        public DimensionsPoolInternal()
        {
            pool = new Dictionary<DimensionsKey, Dimensions>(128);
        }

        public Dimensions Create(int width, int height)
        {
            Dimensions result = null;

            DimensionsKey key = new DimensionsKey(width,height);
            if (!pool.TryGetValue(key, out result))
            {
                Dimensions newObject = new Dimensions(width, height);
                pool[key] = newObject;
                result = newObject;
            }

            return result;
        }

        #region Private fields

        Dictionary<DimensionsKey, Dimensions> pool;

        #endregion
    }

    public class DimensionsKey
    {
        public int Width { get; private set; }
        public int Height { get; private set; }

        public DimensionsKey(int width, int height)
        {
            Width = width;
            Height = height;
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            DimensionsKey dim = obj as DimensionsKey;
            if (dim == null)
                return false;

            return Width == dim.Width && Height == dim.Height;
        }

        public override int GetHashCode()
        {
            if (fHashCode == 0)
            {
                fHashCode = 37 + 17 * Width;
                fHashCode += 15 * Height;
            }

            return fHashCode;
        }

        private int fHashCode;
    }
}
